package com.wisdytech.linkdcs.equipLifeCycle.maintain.service.impl;

import com.wisdytech.common.utils.PojoConvertUtil;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.MaintenanceItemBakDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MTypeItem;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MaintenanceItem;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.ImportExcelUtils;
import com.wisdytech.linkdcs.equipLifeCycle.check.model.CheckModelItem;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMTypeItemDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenanceItemDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MaintenanceItemBak;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.service.IMaintenanceItemService;
import com.wisdytech.linkdcs.partLife.model.Part;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.model.ToolConfig;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2018-06-09
 */
@Service("iMaintenanceItemService")
@Transactional
public class MaintenanceItemServiceImpl extends BaseService<IMaintenanceItemDao, MaintenanceItem> implements IMaintenanceItemService {

	@Resource
	private IMaintenanceItemDao iMaintenanceItemDao;
	@Resource
	private IMTypeItemDao iMTypeItemDao;
    @Resource
    private MaintenanceItemBakDao maintenanceItemBakDao;
	@Override
	public void addItem(MaintenanceItem maintenanceItem, String loginName) {
        EntityWrapper<MaintenanceItem> ew = new EntityWrapper<>();
        //验证备件编码的唯一性
        List<MaintenanceItem> list = new ArrayList<>();
        list = iMaintenanceItemDao.selectPage(new Page<Part>(1, 1), ew.eq("ITEM_CODE", maintenanceItem.getItemCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!list.isEmpty()) {
            throw new ServiceException("该保养项编码被使用");
        }
        String pkId = BaseUtil.getUUID();
        String snapshotId = BaseUtil.getUUID();

        maintenanceItem.setPkId(pkId);
        maintenanceItem.setDelFlag(CommonConstants.DEL_FLAG);
        maintenanceItem.setCreateUser(loginName);
        maintenanceItem.setCreateDate(new Date());
        maintenanceItem.setVersion(snapshotId);
        int partCount = iMaintenanceItemDao.insert(maintenanceItem);
        if (partCount <= 0) {
            throw new ServiceException("新增失败");
        }
        MaintenanceItem snapshot = iMaintenanceItemDao.selectById(pkId);
        MaintenanceItemBak mItem = PojoConvertUtil.convertPojo(snapshot, MaintenanceItemBak.class);
        mItem.setDelFlag(CommonConstants.DEL_FLAG);
        mItem.setPkId(snapshotId);
        this.maintenanceItemBakDao.insert(mItem);
    }

	@Override
	public PageInfo<MaintenanceItem> listItemByFilter(String itemCode, String itemName, Filter filter) {
		EntityWrapper<MaintenanceItem> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(itemCode)) {
        	ew.like("ITEM_CODE", itemCode);
        }
        if (StringUtils.isNotBlank(itemName)) {
        	ew.like("ITEM_NAME", itemName);
        }
		List<MaintenanceItem> list =super.beforeList(IMaintenanceItemDao.class, filter).selectList(ew.eq("del_flag", CommonConstants.DEL_FLAG));
		PageInfo<MaintenanceItem> page = new PageInfo<>(list);
		return page;
	}

	@Override
	public MaintenanceItem getItemById(String pkId) {
		return iMaintenanceItemDao.selectById(pkId);
	}

	@Override
	public void updateItem(MaintenanceItem maintenanceItem, String loginName) {
        EntityWrapper<MaintenanceItem> ew = new EntityWrapper<>();;
        //验证备件编码的唯一性--修改功能
        List<MaintenanceItem> list;
        list = iMaintenanceItemDao.selectPage(new Page<Part>(1, 1),ew.eq("ITEM_CODE", maintenanceItem.getItemCode()).ne("pk_id", maintenanceItem.getPkId()));
        if (list.size() > 0){
            throw new ServiceException("该保养项编码被使用");
        }
        String snapshotId = BaseUtil.getUUID();
        maintenanceItem.setUpdateDate(new Date());
        maintenanceItem.setUpdateUser(loginName);
        maintenanceItem.setVersion(snapshotId);
        int operationCount = iMaintenanceItemDao.updateById(maintenanceItem);
        if (operationCount <= 0) {
            throw new ServiceException("修改失败");
        }
        MaintenanceItem snapshot = iMaintenanceItemDao.selectById(maintenanceItem.getPkId());
        MaintenanceItemBak mItem = PojoConvertUtil.convertPojo(snapshot, MaintenanceItemBak.class);
        mItem.setDelFlag(CommonConstants.DEL_FLAG);
        mItem.setPkId(snapshotId);
        this.maintenanceItemBakDao.insert(mItem);
    }

	@Override
	public void delItemById(String ids) {
        List<String> idList = new ArrayList<String>();
        String[] id = ids.split(",");
        for (int i = 0; i < id.length; i++) {
            idList.add(id[i]);
        }
        for(String pkId : id) {
            EntityWrapper<MTypeItem> ew = new EntityWrapper<>();
            ew.eq("ITEM_ID", pkId);
            int num = this.iMTypeItemDao.selectCount(ew);
            if(num>0) {
            	throw new ServiceException("所选记录中存在被保养类别关联");
            }
        }
        int partCount = iMaintenanceItemDao.deleteBatchIds(idList);
        if (partCount <= 0) {
            throw new ServiceException("删除失败");
        }
	}

	@Override
	public PageInfo<MaintenanceItem> listPlanAndItemByFilter(String pkId, Filter filter) {
		List<MaintenanceItem> list =super.beforeList(IMaintenanceItemDao.class, filter).listPlanAndItemByFilter(pkId);
		PageInfo<MaintenanceItem> page = new PageInfo<>(list);
		return page;
	}

	@Override
	public PageInfo<MaintenanceItem> listTaskConfirmItemByFilter(String pkId, Filter filter) {
		List<MaintenanceItem> list =super.beforeList(IMaintenanceItemDao.class, filter).listTaskConfirmItemByFilter(pkId);
		PageInfo<MaintenanceItem> page = new PageInfo<>(list);
		return page;
	}

	@Override
	public void batchImportItem(MultipartFile file, SysUser operator) {

        if (file == null) {
            throw new ServiceException("文件为空");
        }
        if (operator ==null) {
            throw new ServiceException("操作人不能为空");
        }
        int errorRow=0;
        try {
            String fileName = file.getOriginalFilename();
            InputStream in = file.getInputStream();
            List<List<Object>> data = ImportExcelUtils.getDataListByExcel(in, fileName);
            if (data == null || data.size() == 0) {
                throw new ServiceException("表格数据为空");
            }
            List<ToolConfig> list = new ArrayList<>();
            //i 从1开始，去除表头数据，根据自己的模板而定
            for (int i = 1; i < data.size(); i++) {
            	  errorRow = i;
            	  MaintenanceItem item = new MaintenanceItem();
            	  item.setPkId(BaseUtil.getUUID());
            	  item.setCreateDate(new Date());
            	  item.setCreateUser(operator.getUsername());
            	  item.setDelFlag(CommonConstants.DEL_FLAG);
                  if (data.get(i).get(0) == null||StringUtils.isBlank(data.get(i).get(0).toString())) {
                      throw new ServiceException("第"+i+"行第1列保养项编码数据不能为空");
                  }
                  if(!checkItemCode(data.get(i).get(0).toString())) {
                      throw new ServiceException("第"+i+"行第1列保养项编码已存在");
                  }
                  item.setItemCode(data.get(i).get(0).toString());
                  if (data.get(i).get(1) == null||StringUtils.isBlank(data.get(i).get(1).toString())) {
                      throw new ServiceException("第"+i+"行第2列保养项名称数据不能为空");
                  }
                  item.setItemName(data.get(i).get(1).toString());
                  item.setMaintenanceMethod(data.get(i).get(2).toString());
                  item.setToolSupplies(data.get(i).get(3).toString());
                  if (data.get(i).get(4) == null||StringUtils.isBlank(data.get(i).get(4).toString())) {
                      throw new ServiceException("第"+i+"行第5列停机项数据不能为空");
                  }
                  item.setStopItem(data.get(i).get(4).toString());
                  if (data.get(i).get(5) == null||StringUtils.isBlank(data.get(i).get(5).toString())) {
                      throw new ServiceException("第"+i+"行第6列品质项数据不能为空");
                  }
                  item.setQualityItem(data.get(i).get(5).toString());
                  if(data.get(i).size()>6) {
                      item.setRemark(data.get(i).get(6).toString());
                  }

                  String pkId = BaseUtil.getUUID();
                  item.setVersion(pkId);
                  iMaintenanceItemDao.insert(item);
                  //新增快照
                  MaintenanceItemBak bak = new MaintenanceItemBak();
                  bak.setPkId(pkId);
                  bak.setCreateDate(new Date());
                  bak.setCreateUser(operator.getUsername());
                  bak.setDelFlag(CommonConstants.DEL_FLAG);
                  bak.setItemCode(item.getItemCode());
                  bak.setItemName(item.getItemName());
                  bak.setMaintenanceMethod(item.getMaintenanceMethod());
                  bak.setQualityItem(item.getQualityItem());
                  bak.setRemark(item.getRemark());
                  bak.setToolSupplies(item.getToolSupplies());
                  bak.setStopItem(item.getStopItem());
                  maintenanceItemBakDao.insert(bak);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传文件出错");
        } catch (IndexOutOfBoundsException e2) {
            e2.printStackTrace();
            throw new ServiceException("表格中第"+errorRow+"存在空数据");
        } 
		
	}

	private boolean checkItemCode(String string) {
		EntityWrapper<MaintenanceItem> ew = new EntityWrapper<>();
        //验证备件编码的唯一性
        List<MaintenanceItem> list = new ArrayList<>();
        list = iMaintenanceItemDao.selectPage(new Page<Part>(1, 1), ew.eq("ITEM_CODE", string).eq("del_flag", CommonConstants.DEL_FLAG));
		return list.isEmpty();
	}

}
